import java.util.Arrays;

public class MyHeap {
    public int[] elem;
    public int usedSize;

    public int[] array = {27, 15, 19, 18, 28, 34, 65, 49, 25, 37};
    public MyHeap(int size) {
        this.elem = new int[size];
    }

    public void createArray() {
        for(int i = 0; i < 10; i++) {
            elem[i] = array[i];
            usedSize++;
        }
    }

    //创建一个大根堆
    public void createHeap() {

        //找到最后一颗子树
        for(int parent = (usedSize - 1) / 2; parent >= 0; parent--) {
            softDown(parent);
        }
    }
    //交换
    public void swap(int parent, int child) {
        int tmp = elem[parent];
        elem[parent] = elem[child];
        elem[child] = tmp;
    }

    //向下调整
    public void softDown(int parent) {
        int child = parent * 2 + 1;
        while(child < usedSize) {
            if(child + 1 < usedSize && elem[child] < elem[child + 1]) {
                child = child + 1;
            }
            if(elem[child] > elem[parent]) {
                swap(parent, child);
                child = parent;
                parent = (parent - 1) / 2;
            }else {
                break;
            }


        }
    }

    //判断是否为满
    public boolean isFull() {
        return elem.length == usedSize;
    }

    //插入一个元素
    public void push(int val) {
        //判断是否为满，如果满了就扩容
        if(isFull()) {
            elem = Arrays.copyOf(elem, elem.length * 2);
        }
        elem[usedSize] = val;
        usedSize++;
        //向上调整
        softUp();

    }

    public void softUp() {
        int parent = (usedSize - 2) / 2;
        int child = usedSize - 1;
        while(child > 0) {
            if(elem[child] > elem[parent]) {
                swap(parent, child);
                child = parent;
                parent = (parent - 1 ) / 2;
            }else {
                break;
            }
        }
    }

    public boolean isEmpty() {
        return usedSize == 0;
    }
    //删除一个元素(堆的首部元素)
    public int pop() {
        //判断是否为空
        if(isEmpty()) {
            throw new RuntimeException("堆为空");
        }
        int ret = elem[0];
        swap(0, usedSize - 1);
        usedSize--;
        softDown(0);
        return ret;
    }

    public static void main(String[] args) {
        MyHeap m = new MyHeap(10);
        m.createArray();
        m.createHeap();
        m.push(100);
        System.out.println(Arrays.toString(m.elem));

        System.out.println("出队列元素为：" + m.pop());
        System.out.println(Arrays.toString(m.elem));

    }
}
